package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.Vo.MenusVo;
import com.kang.bean.Menus;
import com.kang.mapper.MenusMapper;
import com.kang.service.MenusService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: photo_fawu
 * @description:
 * @author: K.faWu
 * @create: 2021-11-15 16:38
 **/
@Service
public class MenusServiceImpl extends ServiceImpl<MenusMapper, Menus> implements MenusService {
    @Autowired
    private MenusMapper menusMapper;

    @Override
    public List<MenusVo> getAll() {
        List<Menus> menus = menusMapper.selectList(new QueryWrapper<>());
        // 顶级菜单
        ArrayList<MenusVo> top = new ArrayList<>();
        for(Menus m:menus){
            if(m.getPid() == -1){
                //将最高级菜单装进集合
                MenusVo menusVo = new MenusVo();
                BeanUtils.copyProperties(m, menusVo);
                top.add(menusVo);
            }
        }
        //将次级菜单装进顶级菜单中
        for(MenusVo t:top){
            setChildren(t,menus);
        }
        return top;
    }


    public void setChildren(MenusVo top, List<Menus> menus) {
        List<MenusVo> childs = new ArrayList<>();

        for(Menus m:menus){
            //菜单的父id等于top的id，说明是top的次级菜单
            if(m.getPid().equals(top.getId())){
                MenusVo menusVo = new MenusVo();
                BeanUtils.copyProperties(m, menusVo);
                childs.add(menusVo);
            }
        }
        top.setNodes(childs);
        if(childs.size() > 0){
            for(MenusVo child : childs){
                this.setChildren(child, menus);
            }
        }
    }
}
